using System.Windows.Controls;
using System.Windows.Input;

namespace DimensionsHelper.Client.Commands;

public static class TextBoxCommands
{

    private static readonly Lock Synchronize = new();

    private static RoutedUICommand? _increaseIntegerCommand;
    private static RoutedUICommand? _decreaseIntegerCommand;

    public static RoutedUICommand IncreaseIntegerCommand =>
        EnsureCommand(ref _increaseIntegerCommand, "IncreaseInteger");

    public static RoutedUICommand DecreaseIntegerCommand =>
        EnsureCommand(ref _decreaseIntegerCommand, "DecreaseInteger");



    static TextBoxCommands()
    {
        CommandManager.RegisterClassCommandBinding(typeof(TextBox),
            new CommandBinding(IncreaseIntegerCommand, IncreaseInteger));
        CommandManager.RegisterClassCommandBinding(typeof(TextBox),
            new CommandBinding(DecreaseIntegerCommand, DecreaseInteger));
    }


    private static RoutedUICommand EnsureCommand(ref RoutedUICommand? command, string commandPropertyName)
    {
        lock (Synchronize)
        {
            command ??= new RoutedUICommand(commandPropertyName, commandPropertyName, typeof(TextBoxCommands));
        }

        return command;
    }


    private static void IncreaseInteger(object sender, RoutedEventArgs e)
    {
        if (sender is not TextBox textBox)
        {
            return;
        }
        
        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.Text = "1";
            return;
        }

        if (!double.TryParse(textBox.Text, out double doubleValue))
        {
            return;
        }

        textBox.Text = ((int)(doubleValue + 1)).ToString();
    }


    private static void DecreaseInteger(object sender, RoutedEventArgs e)
    {
        if (sender is not TextBox textBox)
        {
            return;
        }
        
        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.Text = "-1";
            return;
        }

        if (!double.TryParse(textBox.Text, out double doubleValue))
        {
            return;
        }

        textBox.Text = ((int)(doubleValue - 1)).ToString();
    }

}